package game.bluetooth;

import game.main.GameActivity;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.UUID;

import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothServerSocket;
import android.bluetooth.BluetoothSocket;
import android.graphics.Point;

public class Server implements Bluetooth {
	public static final String NAME = "tic-tac-toe";
	public static final UUID uuid = UUID.fromString("57215830-32fb-11e3-aa6e-0800200c9a66");
	private GameActivity gameActivity;

	private BluetoothServerSocket serverSocket;
	private BluetoothSocket socket = null;

	private InputStream inStream;
	private OutputStream outStream;
	private BluetoothAdapter adapter = BluetoothAdapter.getDefaultAdapter();

	public Server(GameActivity gameActivity) {
		this.gameActivity = gameActivity;
		if (adapter != null && adapter.isEnabled()) {

			try {
				BluetoothServerSocket serverSocket = adapter.listenUsingInsecureRfcommWithServiceRecord(NAME, uuid);
				socket = serverSocket.accept();
			} catch (Exception e) {
				return;
			}

			try {
				if (socket != null) {
					serverSocket.close();
					inStream = socket.getInputStream();
					outStream = socket.getOutputStream();

					BluetoothDevice device = socket.getRemoteDevice();
					updateView(device);
				}
			} catch (Exception e) {
			}
		}
	}

	@Override
	public void send(Point point) {
		try {
			outStream.write(String.format("%d,%d", point.x, point.y).getBytes());
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	@Override
	public Point recive() {
		try {
			byte[] bytes = new byte[1024];
			int lenght;
			lenght = inStream.read(bytes);
			String mensagemRecebida = new String(bytes, 0, lenght);

			try {
				String[] split = mensagemRecebida.split(",");
				int x = Integer.parseInt(split[0]);
				int y = Integer.parseInt(split[1]);
				return new Point(x, y);
			} catch (Exception e) {
				e.printStackTrace();
			}
		} catch (Exception e) {
		}
		return null;
	}

	private void updateView(final BluetoothDevice device) {
		gameActivity.runOnUiThread(new Runnable() {
			@Override
			public void run() {
				Server.this.gameActivity.setDispositivoRemoto(device.getName());
			}
		});
	}

	@Override
	public void close() {
		try {
			if (socket != null)
				socket.close();
			if (serverSocket != null)
				serverSocket.close();
		} catch (Exception e) {
		}
	}
}
